"""
Created on  2024.10.07
@author: <LIN>
使用Gradio调用本机大模型
"""
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
from transformers import TextStreamer

model_name = r"F:\dataset\models\Qwen2.5-0.5B-Instruct"

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# 如果有 GPU，则将模型移动到 GPU 上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)


def generate_text(input_text):
    prompt = input_text
    messages = [
        {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
        {"role": "user", "content": prompt},
    ]
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
    )
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
    # 创建 TextStreamer 对象
    streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)

    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512,
        streamer=streamer,
    )
    generated_ids = [
        output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
    ]

    response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
    return response


iface = gr.Interface(
    fn=generate_text,
    inputs="text",
    outputs="text",
     # 设置为实时更新
)

iface.launch()